/******************************************************************************
 * This file is part of libemb.
 *
 * libemb is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * libemb is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with libemb.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Project: Embedme
 * Author : FergusZeng
 * Email  : cblock@126.com
 * git	  : https://git.oschina.net/cblock/embedme
 * Copyright 2014~2020 @ ShenZhen ,China
*******************************************************************************/
#include "IODevice.h"
#include "Tracer.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

namespace libemb{
/******************************************************************************
* FUNCTION	 :	IODevice()
* DESCRIPTION:	构造函数
* ARGUMENTS	 :
* RETURN	 :	
* NOTES		 :	
******************************************************************************/
IODevice::IODevice():
m_fd(-1),
m_devName(""),
m_openMode(-1)
{
}

IODevice::~IODevice()
{
	close();
}
/**
 *  \brief  打开设备
 *  \param  devName 设备全名(包含路径,如:/dev/ttyS0)
 *  \param  mode 打开模式IO_MODE_E
 *  \return 设备打开成功返回true,失败返回false
 *  \note   none
 */
bool IODevice::open(const char * devName, int mode)
{
	if (NULL==devName ||
		(mode < 0) ||
		(mode > IO_MODE_APPEND_ONLY))
	{
		TRACE_ERR_CLASS("Parameter error.\n");
		return false;
	}

	if (m_fd >= 0)
	{
		TRACE_ERR_CLASS("Device is already opened!\n");
		return false;
	}

	switch(mode)
	{
		case IO_MODE_RD_ONLY:
			m_fd = ::open(devName, O_RDONLY);
			break;
		case IO_MODE_WR_ONLY:
			m_fd = ::open(devName, O_WRONLY);
			break;
		case IO_MODE_RDWR_ONLY:
			m_fd = ::open(devName, O_RDWR);
			break;
		case IO_MODE_APPEND_ONLY:
			m_fd = ::open(devName, O_RDWR, O_CREAT|O_APPEND);
			break;
		default:
			TRACE_ERR_CLASS("Unsupport IO Mode: %d\n",mode);
			return false;
	}

	if (m_fd<0)
	{
		TRACE_ERR_CLASS("Open %s error: %s\n",devName,ERROR_STRING);
		return false;
	}
	m_devName = devName;
	m_openMode = mode;
	return true;
}
/**
 *  \brief  关闭设备
 *  \param  void
 *  \return 设备关闭成功返回true,失败返回false
 *  \note   none
 */
bool IODevice::close()
{
	if (m_fd >=0 )
	{
		::close(m_fd);
		m_fd = -1;
	}
	return true;
}

/**
 *  \brief  设置属性
 *  \return STATUS_ERRROR
 */
int IODevice::setAttribute(int attr, int value)
{
    return STATUS_ERROR;
}

/**
 *  \brief  读取属性
 *  \return STATUS_ERRROR
 */
int IODevice::getAttribute(int attr)
{
    return STATUS_ERROR;
}
}